package com.powernode.service.impl;

import com.powernode.dao.SysMenuDao;
import com.powernode.dao.SysUserDao;
import com.powernode.entity.SysUser;
import com.powernode.vo.SecurityUser;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

@Service
public class userServiceImpl implements UserDetailsService {
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private SysMenuDao sysMenuDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserDao.getByUserName_1(username);
        if(null==sysUser){
            throw new UsernameNotFoundException("账号不存在");
        }
        //获取用户权重并设置给当前用户
        List<String> list = sysMenuDao.queryPermissionByUserId(sysUser.getUserId());
        //使用stream流转换
        List<SimpleGrantedAuthority> grantedAuthorities=list.stream().map(SimpleGrantedAuthority::new).collect(toList());
        SecurityUser securityUser = new SecurityUser(sysUser);
        securityUser.setSimpleGrantedAuthorities(grantedAuthorities);
        return securityUser;
    }
}